#define _CRT_SECURE_NO_WARNINGS 1
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include<math.h>
#include<stdlib.h>
#include<stdio.h>
#include<unordered_map>
#include<queue>
#include<stack>
#include <functional>
#include <memory>
using namespace std;

class Solution {
public:
    int n, m;
    int cutOffTree(vector<vector<int>>& forest) {
        n = forest.size();
        m = forest[0].size();
        vector<pair<int, int>> trees;
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                if (forest[i][j] > 1) trees.push_back({ i,j });
        sort(trees.begin(), trees.end(), [&](const pair<int, int>& p1, const pair<int, int>& p2)
            {
                return forest[p1.first][p1.second] < forest[p2.first][p2.second];
            });

        int bx = 0, by = 0;
        int ret = 0;
        for (auto& p : trees)
        {
            int step = bfs(forest, bx, by, p.first, p.second);
            if (step == -1) return -1;
            ret += step;
            bx = p.first, by = p.second;
        }
        return ret;
    }

    int vist[60][60];
    int dx[4] = { 1,-1,0,0 };
    int dy[4] = { 0,0,1,-1 };
    int bfs(vector<vector<int>>& forest, int bx, int by, int a, int b)
    {
        if (bx == a && by == b) return 0;
        queue<pair<int, int>> qt;
        memset(vist, 0, sizeof(vist));
        qt.push({ bx,by });
        vist[bx][by] = 1;
        int ret = 0;
        while (qt.size())
        {
            int num = qt.size();
            ret++;
            while (num--)
            {
                auto p = qt.front();
                qt.pop();
                for (int i = 0; i < 4; i++)
                {
                    int xi = p.first + dx[i];
                    int yi = p.second + dy[i];
                    if (xi >= 0 && xi < n && yi >= 0 && yi < m && vist[xi][yi] == 0 && forest[xi][yi] >= 1)
                    {
                        if (xi == a && yi == b) return ret;
                        vist[xi][yi] = 1;
                        qt.push({ xi,yi });
                    }
                }
            }
        }
        return -1;
    }
};

int main()
{
    vector<vector<int>> arr = { {1,2,3} ,{0,0,4},{7,6,5} };
    int ret = Solution().cutOffTree(arr);
	return 0;
}